package cn.change.user.service.impl;

import cn.change.basic.dto.LoginDto;
import cn.change.basic.util.AjaxResult;
import cn.change.basic.util.MD5Utils;
import cn.change.user.domain.Logininfo;
import cn.change.user.mapper.LogininfoMapper;
import cn.change.user.service.ILogininfoService;
import cn.change.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lhl
 * @since 2022-04-01
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    public AjaxResult loginAccount(LoginDto loginDto) {
        /*1.校验和判断*/
        if(StringUtils.isEmpty(loginDto.getUsername())
                || StringUtils.isEmpty(loginDto.getPassword())
                || StringUtils.isEmpty(loginDto.getType() == null))
        {
        return AjaxResult.me().setMessage("请输入参数！");}

        // 1.2 判断用户是否存在 Username--username,phone,email
        Logininfo logininfo = logininfoMapper.loadByAcount(loginDto.getUsername(),loginDto.getType());
        if (logininfo == null){
            return AjaxResult.me().setMessage("用户名或密码不正确!");
        }
        // 1.3 判断用户状态是否ok
        //2 比对密码完成登录
        String salt = logininfo.getSalt();
        String password = logininfo.getPassword();

        String inputSecurityPwd = MD5Utils.encrypByMd5(loginDto.getPassword() + salt);
        if (!password.equals(inputSecurityPwd)){
            return AjaxResult.me().setMessage("用户名或密码不正确!");
        }
        //3 记录logininfo到redis，key是token
        String token = UUID.randomUUID().toString();
        /*设置过期时间*/
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //4 返回AjaxResult，如果登录成功，还需要返回token和loginInfo
        HashMap<Object, Object> result = new HashMap<>();
        result.put("token",token);
        //为了安全起见，把前台不会用到铭感信息salt和password去空
        logininfo.setPassword(null);
        logininfo.setUsername(null);
        result.put("logininfo",logininfo);
        return AjaxResult.me().setResultObj(result);

    }
}
